import { Router } from '../../../lib/utils/router/index'
import Auth from '../../auth/index'
import UserLogin from '../../login'

class MyRouter extends Router {
  constructor() {
    super()
    this.init()
    this.instance = null
  }

  static getInstance() {
    if (!this.instance) {
      this.instance = new MyRouter()
    }
    return this.instance
  }

  init() {
    this.interceptor = {
      before: _options => {
        // 获取权限 permission
        if (_options.permission) {
          let permissions = _options.permission.toString().split(',')
          let _hasPermission = true
          for (let i = 0, leng = permissions.length; i < leng; i++) {
            if (!Auth.checkPermission(permissions[i])) {
              _hasPermission = false
              break
            }
          }
          // 如果该用户没有检测的权限，不执行跳转
          if (!_hasPermission) {
            return false
          }
        }
        // 该页面是否需要登录
        if (_options.needLogin) {
          if (!UserLogin.checkIfLogin()) {
            return false
          }
        }
        // TODO 此处可以全局配置页面属性，例如页面是否需要登录，是否需要某个权限
        // if (_options.url) {
        // }
        return _options
      },
      after: null
    }
  }
}

let _myRouter = MyRouter.getInstance()
export default _myRouter
